
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * Mysql class
 *
 * @author renguiquan
 * @date 2019/3/4
 */
public class Mysql {

    static final String sql = "insert into test (uuid) values(?)";

    public static void main(String[] args) throws InterruptedException {
        Integer threadCound = 1;
        Integer dataTotal = 100;
        Thread[] threads = new Thread[threadCound];

        System.out.println(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));

        for (Integer i = 0; i < threadCound; i++) {
            threads[i] = new Thread(new InsertRunner(dataTotal / threadCound));
            threads[i].start();
        }
        for (Integer i = 0; i < threadCound; i++) {
            threads[i].join();
        }

        System.out.println(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
    }

    static class InsertRunner implements Runnable {
        Integer count;

        InsertRunner(Integer count) {
            this.count = count * 10000;
        }

        @Override
        public void run() {
            Connection connection = getConnection();
            for (Integer i = 0; i < count; i++) {
                Mysql.insert(connection);
            }
        }
    }

    private static void insert(Connection connection) {
        PreparedStatement pstmt;
        try {
            pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, UUID.randomUUID().toString());
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static Connection getConnection() {
        String driver = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://192.168.3.108:3306/test";
        String username = "root";
        String password = "root";
        Connection conn = null;
        try {
            Class.forName(driver);
            conn = (Connection) DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
}
